package com.sunday.demo.idGenerator.impl;

import com.sunday.demo.exception.IdGeneratorException;
import com.sunday.demo.idGenerator.LogTranceIdGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Random;

/**
 * @ClassName idGenerator
 * @Author JiangHai
 * @Date 2021/9/4 18:08
 **/
public class RandomIdGenerator implements LogTranceIdGenerator{

    private static final Logger logger = LoggerFactory.getLogger(RandomIdGenerator.class);
    private static final int MAX_RANDOW = 122;

    private static final LogTranceIdGenerator instance = new RandomIdGenerator();

    private static LogTranceIdGenerator create() {
        return instance;
    }

    @Override
    public String generate() {
        String hostName = null;
        try {
            hostName = getLastFieldOfHostName();
        } catch (UnknownHostException e) {
            throw new IdGeneratorException("500","host name is empty");
        }
        String random = generateRandomAlphameric(8);
        return String.format("%s-%d-%s",hostName,System.currentTimeMillis(),random);
    }


    private  String getLastFieldOfHostName() throws UnknownHostException {
        String hostName = InetAddress.getLocalHost().getHostAddress();
        if (hostName == null || hostName.isEmpty()) {
            throw new UnknownHostException();
        }
        return getLastSubstrSplittedByDot(hostName);
    }

    private String getLastSubstrSplittedByDot(String hostName) {
        String[] tokens = hostName.split("\\.");
        return tokens[tokens.length - 1];
    }

    private  String generateRandomAlphameric(int length) {
        if (length <= 0) {
            throw new IllegalArgumentException();
        }
        int count = 0;
        char[] temp = new char[length];
        Random random = new Random();
        while (count < length) {
            int randomAscii = random.nextInt(MAX_RANDOW);
            boolean isLowercase = randomAscii >= '0' && randomAscii <= '9';
            boolean isUppercase = randomAscii >= 'A' && randomAscii <= 'Z';
            boolean isNumber = randomAscii >= 'a' && randomAscii <= 'z';
            if (!isLowercase && !isUppercase && !isNumber) {
                continue;
            }
            temp[count] = (char) randomAscii;
            count++;
        }
        return new String(temp);
    }

    public static void main(String[] args) {
        System.out.println(RandomIdGenerator.create().generate());
    }
}
